<template>
  <div class="flex flex-col h-full">
    <div class="flex justify-between items-center">
      <div class="flex-1 text-center">
        <a-button type="primary" @click="onBack">返回</a-button>
      </div>
      <div class="w-11/12">
        <PatientInfoHeader is-outpatient show-insurance :patient-info="currentPatient">
          <a-divider type="vertical" :style="{ height: '40px', margin: '0 16px' }" />
          <div>
            <div class="flex items-center">
              <LabelValue label="住院号" :width="140" :value="currentPatient.admissionCode" />
              <LabelValue label="手术名称" :width="320" :value="currentPatient.oprName" />
              <LabelValue label="联合手术1" :width="200" :value="currentPatient.jointOprName1" />
              <LabelValue label="手术房间" :width="160" :value="currentPatient.oprRoomName" />
              <LabelValue label="器械护士" :width="160" :value="currentPatient.instrumenttNurseName" />
              <LabelValue label="一助" :width="140" :value="currentPatient.firstNurseName" />
              <LabelValue label="麻醉方式" :width="200" :value="currentPatient.anaesName" />
              <LabelValue label="心电监护" :width="120" :value="currentPatient.isEcg ? '是' : '否'" />
              <LabelValue label="联合手术2" :width="260" :value="currentPatient.jointOprName2" />
              <LabelValue label="联合手术4" :width="260" :value="currentPatient.jointOprName4" />
            </div>
            <div class="flex items-center">
              <LabelValue label="账户余额" :width="140" :value="currentPatient.ye" />
              <LabelValue label="手术医生" :width="320" :value="currentPatient.oprDoctorName" />
              <LabelValue label="嘱托" :width="200" :value="currentPatient.advMemo" />
              <LabelValue label="巡回护士" :width="160" :value="currentPatient.tourNurseName" />
              <LabelValue label="麻醉医生" :width="160" :value="currentPatient.anaesDoctorName" />
              <LabelValue label="二助" :width="140" :value="currentPatient.secondNurseName" />
              <LabelValue label="特殊要求" :width="200" :value="currentPatient.specRequirements" />
              <LabelValue label="复发" :width="120" :value="currentPatient.isRecurrence ? '是' : '否'" />
              <LabelValue label="联合手术3" :width="260" :value="currentPatient.jointOprName3" />
              <LabelValue label="联合手术5" :width="300" :value="currentPatient.jointOprName5" />
              <LabelValue label="联合手术6" :width="260" :value="currentPatient.jointOprName6" />
            </div>
          </div>
        </PatientInfoHeader>
      </div>
    </div>
    <a-card class="flex-1 mt-2">
      <a-form :model="formState" :label-col="{ style: { width: '120px' } }">
        <div class="w-5/6 flex mx-auto">
          <a-form-item label="手术名称" class="w-1/2">
            <a-input v-if="NameEleMode" v-model:value="formState.oprCode" placeholder="请输入" />
            <SelectTable
              v-else
              v-model:value="formState.oprName"
              type="手术icd9"
              @select=";(formState.oprCode = $event.icd9Code), (formState.oprName = $event.icd9Name)"
            />
          </a-form-item>
          <a-form-item label="手术分类" class="w-1/4">
            <SelectItem v-model:value="formState.oprTypeCode" type="DT00037" placeholder="请选择" allow-clear />
          </a-form-item>
          <a-form-item label="部位" class="w-1/4">
            <!-- <a-select v-model:value="formState.oprAptmPartList" placeholder="请选择" mode="multiple" :max-tag-count="1" :options="positionList" allow-clear /> -->
            <SelectPartTags
              :value="{ partCode: formState.oprAptmPartList, partName: formState.oprAptmPartName }"
              multiple
              allow-clear
              show-new
              :input-or-textarea="true"
              type="部位"
              @select=";(formState.oprAptmPartList = $event.partCode || []), (formState.oprAptmPartName = $event.partName)"
            />
          </a-form-item>
        </div>
        <div class="w-5/6 flex mx-auto">
          <a-form-item label="切口等级" class="w-1/4">
            <SelectItem v-model:value="formState.cutLevelCode" type="DT00035" placeholder="请选择" allow-clear />
          </a-form-item>
          <a-form-item label="愈合类别" class="w-1/4">
            <SelectItem v-model:value="formState.healingCategoryCode" type="heal_lv_code" placeholder="请选择" allow-clear />
          </a-form-item>
          <a-form-item label="手术入路" class="w-1/4">
            <SelectItem v-model:value="formState.approachCode" type="DT00036" placeholder="请选择" allow-clear />
          </a-form-item>
        </div>
        <div class="w-5/6 mx-auto">
          <a-divider dashed />
        </div>
        <div class="w-5/6 flex mx-auto">
          <a-form-item label="麻醉医生" name="anaesDoctorName" class="w-1/4">
            <SelectTable
              v-model:value="formState.anaesDoctorName"
              type="医生"
              @select=";(formState.anaesDoctor = $event.empId), (formState.anaesDoctorName = $event.empName)"
            />
          </a-form-item>
          <a-form-item label="麻醉方式" name="anaesCode" class="w-1/4">
            <SelectItem v-model:value="formState.anaesCode" type="DT00012" placeholder="请选择" allow-clear />
          </a-form-item>
          <a-form-item label="麻醉前用药" name="anaesPreDrug" class="w-1/4">
            <a-input v-model:value="formState.anaesPreDrug" placeholder="请输入" allow-clear />
          </a-form-item>
          <a-form-item label="手术麻醉总时间" class="w-1/4">
            <a-input-number v-model:value="formState.anaesHour" :min="0" placeholder="请输入" class="w-2/6" />
            <span class="mx-2">小时</span>
            <a-input-number v-model:value="formState.anaesMinute" :min="0" placeholder="请输入" allow-clear class="w-2/6" />
            <span class="ml-2">分钟</span>
          </a-form-item>
        </div>
        <div class="w-5/6 flex mx-auto">
          <a-form-item label="联合手术1" name="jointOprName1" class="w-1/4">
            <SelectTable
              v-model:value="formState.jointOprName1"
              type="手术icd9"
              @select=";(formState.jointOprCode1 = $event.icd9Code), (formState.jointOprName1 = $event.icd9Name)"
            />
          </a-form-item>
          <a-form-item label="联合手术2" name="jointoprName2" class="w-1/4">
            <SelectTable
              v-model:value="formState.jointOprName2"
              type="手术icd9"
              @select=";(formState.jointOprCode2 = $event.icd9Code), (formState.jointOprName2 = $event.icd9Name)"
            />
          </a-form-item>
          <a-form-item label="联合手术3" name="jointoprName3" class="w-1/4">
            <SelectTable
              v-model:value="formState.jointOprName3"
              type="手术icd9"
              @select=";(formState.jointOprCode3 = $event.icd9Code), (formState.jointOprName3 = $event.icd9Name)"
            />
          </a-form-item>
          <a-form-item label="联合手术4" name="jointoprName4" class="w-1/4">
            <SelectTable
              v-model:value="formState.jointOprName4"
              type="手术icd9"
              @select=";(formState.jointOprCode4 = $event.icd9Code), (formState.jointOprName4 = $event.icd9Name)"
            />
          </a-form-item>
        </div>
        <div class="w-5/6 flex mx-auto">
          <a-form-item label="联合手术5" name="jointoprName5" class="w-1/4">
            <SelectTable
              v-model:value="formState.jointOprName5"
              type="手术icd9"
              @select=";(formState.jointOprCode5 = $event.icd9Code), (formState.jointOprName5 = $event.icd9Name)"
            />
          </a-form-item>
          <a-form-item label="联合手术6" name="jointoprName6" class="w-1/4">
            <SelectTable
              v-model:value="formState.jointOprName6"
              type="手术icd9"
              @select=";(formState.jointOprCode6 = $event.icd9Code), (formState.jointOprName6 = $event.icd9Name)"
            />
          </a-form-item>
          <a-form-item label="麻醉药及用量" name="anaesDrug" class="w-1/4">
            <a-input v-model:value="formState.anaesDrug" placeholder="请输入" allow-clear />
          </a-form-item>
          <a-form-item label="手术种类" name="oprType" class="w-1/4">
            <a-radio-group v-model:value="formState.oprType">
              <a-radio :value="'1'">大</a-radio>
              <a-radio :value="'2'">中</a-radio>
              <a-radio :value="'3'">小</a-radio>
            </a-radio-group>
          </a-form-item>
        </div>
        <div class="w-5/6 flex mx-auto">
          <a-form-item label="麻醉过程" class="w-full">
            <BaseTable
              :loading="loading"
              column-code="000119"
              max-fill
              :extra-height="60"
              :data-source="operationProcess"
              :scroll="{ x: 1200 }"
              :row-class-name="(record) => (record.isNew ? 'table-row-new' : '')"
            >
              <template #bodyCell="{ column, record, index }">
                <template v-if="column.dataIndex === 'xh'">
                  <div>{{ index + 1 }}</div>
                </template>
                <template v-if="column.dataIndex === 'recDate'">
                  <EditCell title="登记日期">
                    <a-date-picker v-model:value="record.recDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD" @change="onDateChange(record)" />
                  </EditCell>
                </template>
                <template v-if="column.dataIndex === 'recTime'">
                  <EditCell title="登记时间">
                    <a-time-picker v-model:value="record.recTime" value-format="HH:mm" format="HH:mm" class="w-full" @change="onDateChange(record)" />
                  </EditCell>
                </template>
                <template v-if="column.dataIndex === 'sbp'">
                  <EditCell title="收缩压">
                    <a-input v-model:value="record.sbp" v-input:float.2 placeholder="请输入" @blur="onCellBlur($event, record)" />
                  </EditCell>
                </template>
                <template v-if="column.dataIndex === 'dbp'">
                  <EditCell title="舒张压">
                    <a-input v-model:value="record.dbp" v-input:float.2 placeholder="请输入" @blur="onCellBlur($event, record)" />
                  </EditCell>
                </template>
                <template v-if="column.dataIndex === 'pulse'">
                  <EditCell title="脉搏">
                    <a-input v-model:value="record.pulse" v-input:float.2 placeholder="请输入" @blur="onCellBlur($event, record)" />
                  </EditCell>
                </template>
                <template v-if="column.dataIndex === 'breathe'">
                  <EditCell title="呼吸">
                    <a-input v-model:value="record.breathe" v-input:float.2 placeholder="请输入" @blur="onCellBlur($event, record)" />
                  </EditCell>
                </template>
                <template v-if="column.dataIndex === 'bloodDrug'">
                  <EditCell title="输血输液及用药">
                    <a-input v-model:value="record.bloodDrug" v-input:float.2 placeholder="请输入" @blur="onCellBlur($event, record)" />
                  </EditCell>
                </template>
                <template v-if="column.dataIndex === 'action'">
                  <BaseButton confirm-text="确认删除手术过程?" size="small" type="text" danger @click="onDelete(record)">删除</BaseButton>
                </template>
              </template>
              <template #footer>
                <div class="text-center sticky bottom-0">
                  <a-button type="primary" class="mr-2" ghost :icon="h(PlusOutlined)" @click="onAdd()"> 新增一行 </a-button>
                </div>
              </template>
            </BaseTable>
          </a-form-item>
        </div>
        <div class="w-5/6 flex mx-auto">
          <a-form-item label="手术记录" name="oprRecord" class="w-full">
            <a-textarea v-model:value="formState.oprRecord" placeholder="请输入" allow-clear :auto-size="{ minRows: 4, maxRows: 8 }" />
          </a-form-item>
        </div>
        <div class="w-5/6 flex mx-auto">
          <a-form-item label="术后诊断" name="oprIcd10Name" class="w-full">
            <SelectTable v-model:value="formState.oprIcd10Name" type="诊断" @select="onSelect('oprIcd10Name', 'oprIcd10', $event)" />
          </a-form-item>
        </div>
        <div class="w-5/6 mx-auto">
          <a-divider dashed />
        </div>
        <div class="w-5/6 flex mx-auto">
          <a-form-item label="手术日期" name="oprDate" class="w-1/5">
            <a-date-picker v-model:value="formState.oprDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD" class="w-full" />
          </a-form-item>
          <a-form-item label="手术入室时间" name="inRoomeTime" class="w-1/5">
            <a-time-picker v-model:value="formState.inRoomeTime" value-format="HH:mm" format="HH:mm" class="w-full" />
          </a-form-item>
          <a-form-item label="手术开始时间" name="oprTime" class="w-1/5">
            <a-time-picker v-model:value="formState.oprTime" value-format="HH:mm" format="HH:mm" class="w-full" />
          </a-form-item>
          <a-form-item label="手术结束时间" name="oprEdTime" class="w-1/5">
            <a-time-picker v-model:value="formState.oprEdTime" value-format="HH:mm" format="HH:mm" class="w-full" />
          </a-form-item>
          <a-form-item label="手术出室时间" name="outRoomTime" class="w-1/5">
            <a-time-picker v-model:value="formState.outRoomTime" value-format="HH:mm" format="HH:mm" class="w-full" />
          </a-form-item>
        </div>
        <div class="w-5/6 flex mx-auto">
          <a-form-item label="手术医生" name="oprDoctor" class="w-1/5">
            <SelectTable
              v-model:value="formState.oprDoctorName"
              type="医生"
              @select=";(formState.oprDoctor = $event.empId), (formState.oprDoctorName = $event.empName)"
            />
          </a-form-item>
          <a-form-item label="一助" name="firstNurseName" class="w-1/5">
            <SelectTable
              v-model:value="formState.firstNurseName"
              type="医生"
              :search-params="{ emplb: '2' }"
              @select=";(formState.firstNurse = $event.empId), (formState.firstNurseName = $event.empName)"
            />
          </a-form-item>
          <a-form-item label="二助" name="secondNurseName" class="w-1/5">
            <SelectTable
              v-model:value="formState.secondNurseName"
              type="医生"
              :search-params="{ emplb: '2' }"
              @select=";(formState.secondNurse = $event.empId), (formState.secondNurseName = $event.empName)"
            />
          </a-form-item>
          <a-form-item label="器械护士" name="instrumenttNurse" class="w-1/5">
            <SelectTable
              v-model:value="formState.instrumenttNurseName"
              type="职责护士"
              @select=";(formState.instrumenttNurse = $event.empId), (formState.instrumenttNurseName = $event.empName)"
            />
          </a-form-item>
          <a-form-item label="巡回护士" name="tourNurse" class="w-1/5">
            <SelectTable
              v-model:value="formState.tourNurseName"
              type="职责护士"
              @select=";(formState.tourNurse = $event.empId), (formState.tourNurseName = $event.empName)"
            />
          </a-form-item>
        </div>
        <div class="w-5/6 flex mx-auto">
          <a-form-item label="特殊要求" name="specRequirements" class="w-2/4">
            <a-input v-model:value="formState.specRequirements" placeholder="请输入" allow-clear />
          </a-form-item>
          <div class="w-2/4 flex mx-auto justify-end">
            <a-button type="primary" :disabled="saveBtnState" @click="saveOperationRecord">保存</a-button>
          </div>
        </div>
      </a-form>
    </a-card>
  </div>
</template>

<script setup>
import { ref, h, watch } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'
import SelectTable from '@/components/SelectTable'
import EditCell from '@/components/EditCell'
import { post } from '@/utils/request'
import userStore from '../store'

const store = userStore()
const currentPatient = ref({})
const formState = ref({
  oprMrecordAnaesList: [],
  oprDate: null
})
const saveBtnState = ref(false)
const operationProcess = ref([])
const loading = ref(false)
const router = useRouter()
currentPatient.value = store.patientInfo
watch(
  () => formState.value,
  (val) => {
    if (hasValue(val, formArr) || (operationProcess.value && operationProcess.value.length > 0)) {
      saveBtnState.value = false
    } else {
      saveBtnState.value = true
    }
  },
  {
    deep: true
  }
)
const onDateChange = () => {
  saveTableRecord()
}
const onCellBlur = (e) => {
  //过滤键盘Tab事件
  if (!e.relatedTarget) {
    saveTableRecord()
  }
}
const saveTableRecord = () => {
  const recordArr = operationProcess.value.filter((item) => item.isNew)
  if (recordArr && recordArr.length > 0) {
    recordArr.forEach(async (item) => {
      const { code, msg } = await post('oprOperation/opr/doSaveOperationMRecordANAESInfo', {
        ...item,
        oprLsh: currentPatient.value.oprLsh
      })
      if (code !== 0) return message.error(msg)
      message.success(msg || '保存成功')
      getOperationRecordInfo()
    })
  }
}

const getOperationRecordInfo = async () => {
  loading.value = true
  const { code, data, msg } = await post('oprOperation/opr/getOperationMRecordInfo', {
    oprLsh: currentPatient.value.oprLsh
  })
  if (code !== 0) return message.error(msg)
  loading.value = false
  operationProcess.value = data.oprMrecordAnaesList
  formState.value = data
  if (!formState.value.oprDate) formState.value.oprDate = store.operationDate
  formState.value.oprType = data.oprType
}
const saveOperationRecord = async () => {
  if (formState.value.oprTime && formState.value.oprEdTime) {
    if (dayjs(formState.value.oprTime, 'HH:mm').isAfter(dayjs(formState.value.oprEdTime, 'HH:mm'))) {
      message.warning('手术结束时间不可早于手术开始时间')
      return
    }
  }
  const { code, msg } = await post('oprOperation/opr/doSaveOperationMRecordInfo', {
    ...formState.value,
    oprType: formState.value.oprType,
    oprLsh: currentPatient.value.oprLsh,
    keyLsh: currentPatient.value.keyLsh
  })
  if (code !== 0) return message.error(msg)
  message.success(msg || '操作成功')
  getOperationRecordInfo()
}
const onSelect = (value, code, select) => {
  formState.value[value] = select.zdmc
  formState.value[code] = select.zddm
}
const hasValue = (obj, keys) => {
  return keys.some(function (key) {
    return obj[key]
  })
}
const formArr = [
  'anaesDoctorName',
  'anaesCode',
  'anaesPreDrug',
  'anaesHour',
  'anaesMinute',
  'jointOprName1',
  'jointoprName2',
  'anaesDrug',
  'oprType',
  'oprRecord',
  'oprIcd10Name',
  'oprDate',
  'oprTime',
  'oprEdTime',
  'oprDoctor',
  'firstNurseName',
  'secondNurseName',
  'instrumenttNurse',
  'tourNurse',
  'specRequirements'
]

const onAdd = () => {
  const key = `row-${operationProcess.value.length}`
  operationProcess.value.push({
    key,
    recDate: dayjs().format('YYYY-MM-DD'),
    recTime: dayjs().format('HH:mm:ss'),
    sbp: '',
    dbp: '',
    pulse: '',
    breathe: '',
    bloodDrug: '',
    isNew: true
  })
}
const onDelete = async (record) => {
  if (record.isNew) {
    operationProcess.value = operationProcess.value.filter((item) => item.key !== record.key)
  } else {
    const { code, msg } = await post('oprOperation/opr/doDeleteOperationMRecordANAESInfo', {
      id: record.id,
      oprLsh: currentPatient.value.oprLsh
    })
    if (code !== 0) return message.error(msg)
    message.success(msg || '删除成功')
    getOperationRecordInfo()
  }
}

const onBack = () => {
  router.back()
}
if (Object.keys(currentPatient.value).length === 0) {
  onBack()
} else {
  getOperationRecordInfo()
}
const NameEleMode = ref(true)
onMounted(() => {
  NameEleMode.value = getSystemConfig('OPERATION_APPLY_INPUT_MODE') === '0' //手术申请名称输入模式 0：手工输入模式|1：ICD9选择模式
})
</script>

<style lang="less" scoped></style>
